cwd=`pwd`
ccFile=compile_commands.json
buildFolder=.build
rightFolder=basic


#echo -e "\033[44;37;5m ME\033[0m COOL"
#https://blog.csdn.net/felix_f/article/details/12433171
# $1: 1:info 2:error
PrintMSG(){
  if [ $1 -eq 1 ]; then
    echo -e "\033[44;37;1m\033[32m[duck info]\t$2\033[0m"
  fi
  if [ $1 -eq 2 ]; then
    echo -e "\033[44;37;1m\033[31m[duck error]\t$2\033[0m"
  fi
}

PrintMSG 1 "the current directory is:$cwd"

# make sure you are under the right foler.
if [ ! -d $cwd/src ]; then
  PrintMSG 2 "you should execute this sh under the right folder, which is '$rightFolder/':"
  exit
fi

if [ ! -d $cwd/$buildFolder ]; then
  mkdir -p $buildFolder
  PrintMSG 1 "creating a new build folder called:'$buildFolder/'";
else
  if [ $# -ge 1 ]; then
    if [ $1 -eq 1 ]; then
      PrintMSG 1 "force rm build folder and creating a new one called:'$buildFolder/'";
      rm -rf $buildFolder
      mkdir -p $buildFolder
      rm -rf lib
    fi
  fi
fi

cd $cwd/$buildFolder

PrintMSG 1 "building..."
if [ $2 -eq 1 ]; then
  cmake -GNinja -Dccfile=ON -Ddebug=ON -Dtest=ON ..
else
  cmake -GNinja -Dccfile=ON -Ddebug=ON -Dtest=OFF ..
fi

PrintMSG 1 "making soft link..."
if [ -f $cwd/$buildFolder/$ccFile ]; then
  if [ -f $cwd/$ccFile ]; then
    rm $cwd/$ccFile
  fi
  ln -s $cwd/$buildFolder/$ccFile $cwd
else
  PrintMSG 2 "there is no $ccFile exist under $buildFolder folder. building terminated."
  exit
fi

PrintMSG 1 "compiling..."
#cmake --build .
ninja -j 12

PrintMSG 1 "installing..."
ninja install

if [ $# -ge 2 ]; then
  if [ $2 -eq 1 ]; then
    PrintMSG 1 "testing..."
    cd $cwd/$buildFolder
    ./test_basic
  fi
fi
